import 'dart:async';

import 'dart:convert';

import 'package:collection/collection.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:get/get.dart';

import '../../../core/controller/im_controller.dart';
import '../../../routes/app_navigator.dart';
import '../../conversation/conversation_logic.dart';

enum JoinGroupMethod { search, qrcode, invite }

class GroupProfilePanelLogic extends GetxController {
  final conversationLogic = Get.find<ConversationLogic>();
  final imLogic = Get.find<IMController>();
  final isJoined = false.obs;
  final members = <GroupMembersInfo>[].obs;
  late Rx<GroupInfo> groupInfo;
  late JoinGroupMethod joinGroupMethod;

  late StreamSubscription sub;
  late StreamSubscription joinedGroupAddedSub;
  late StreamSubscription memberAddedSub;

  @override
  void onInit() {
    groupInfo = Rx(GroupInfo(groupID: Get.arguments['groupID']));
    joinGroupMethod = Get.arguments['joinGroupMethod'];
    sub = imLogic.groupApplicationChangedSubject.listen(_onChanged);
    joinedGroupAddedSub = imLogic.joinedGroupAddedSubject.listen(_onChanged);
    memberAddedSub = imLogic.memberAddedSubject.listen(_onChanged);
    _checkGroup();
    _getGroupInfo();
    _getMembers();
    super.onInit();
  }

  _onChanged(dynamic value) {
    if (value is GroupApplicationInfo) {
      if (value.groupID == groupInfo.value.groupID && value.handleResult == 1) {
        if (!isJoined.value) {
          isJoined.value = true;
          _getGroupInfo();
          _getMembers();
        }
      }
    } else if (value is GroupInfo) {
      if (value.groupID == groupInfo.value.groupID) {
        if (!isJoined.value) {
          isJoined.value = true;
          _getGroupInfo();
          _getMembers();
        }
      }
    } else if (value is GroupMembersInfo) {
      if (value.groupID == groupInfo.value.groupID && value.userID == OpenIM.iMManager.userID) {
        if (!isJoined.value) {
          isJoined.value = true;
          _getGroupInfo();
          _getMembers();
        }
      }
    }
  }

  _getGroupInfo() async {
    var list = await OpenIM.iMManager.groupManager.getGroupsInfo(
      groupIDList: [groupInfo.value.groupID],
    );
    var info = list.firstOrNull;
    if (null != info) {
      groupInfo.update((val) {
        val?.groupName = info.groupName;
        val?.faceURL = info.faceURL;
        val?.memberCount = info.memberCount;
        val?.groupType = info.groupType;
        val?.createTime = info.createTime;
      });
    }
  }

  _checkGroup() async {
    isJoined.value = await OpenIM.iMManager.groupManager.isJoinedGroup(
      groupID: groupInfo.value.groupID,
    );
  }

  _getMembers() async {
    var list = await OpenIM.iMManager.groupManager.getGroupMemberList(
      groupID: groupInfo.value.groupID,
      count: 10,
    );
    members.assignAll(list);
  }

  enterGroup() async {
    if (isJoined.value) {
      conversationLogic.toChat(
        groupID: groupInfo.value.groupID,
        nickname: groupInfo.value.groupName,
        faceURL: groupInfo.value.faceURL,
        sessionType: groupInfo.value.sessionType,
      );
    } else {
      // 新人入群时，优先检查是否需要收费
      final paymentInfo = await _checkGroupPaymentStatus(groupInfo.value.groupID);
      if (paymentInfo['requiresPayment'] == true) {
        if (paymentInfo['hasPaid'] == true) {
          // 已支付，按原流程进入验证/入群
          AppNavigator.startSendVerificationApplication(
            groupID: groupInfo.value.groupID,
            joinGroupMethod: joinGroupMethod,
          );
        } else {
          // 未支付，优先弹出收费页面
          AppNavigator.startGroupPayment(
            groupInfo: groupInfo.value,
            groupId: groupInfo.value.groupID!,
            inviteCode: null,
            inviterUserId: null,
            groupFee: (paymentInfo['fee'] as double?) ?? 0.0,
          );
        }
      } else {
        // 不需要收费，按原流程
        AppNavigator.startSendVerificationApplication(
          groupID: groupInfo.value.groupID,
          joinGroupMethod: joinGroupMethod,
        );
      }
    }
  }

  @override
  void onClose() {
    sub.cancel();
    joinedGroupAddedSub.cancel();
    memberAddedSub.cancel();
    super.onClose();
  }

  Future<Map<String, dynamic>> _checkGroupPaymentStatus(String groupId) async {
    try {
      // 获取最新群信息，解析 ex 字段中的群收费配置
      final groupsInfo = await OpenIM.iMManager.groupManager.getGroupsInfo(
        groupIDList: [groupId],
      );
      final info = groupsInfo.isNotEmpty ? groupsInfo.first : null;
      if (info == null) {
        return {
          'requiresPayment': false,
          'hasPaid': false,
          'fee': 0.0,
        };
      }

      bool requiresPayment = false;
      double fee = 0.0;

      if (info.ex != null && info.ex!.isNotEmpty) {
        try {
          final exData = jsonDecode(info.ex!);
          if (exData is Map<String, dynamic> && exData.containsKey('groupFee')) {
            final feeData = exData['groupFee'];
            if (feeData is Map<String, dynamic>) {
              requiresPayment = feeData['enabled'] ?? false;
              fee = (feeData['amount'] ?? 0.0).toDouble();
            }
          }
        } catch (e) {
          // ex 解析失败，不影响主流程
        }
      }

      if (!requiresPayment) {
        return {
          'requiresPayment': false,
          'hasPaid': false,
          'fee': 0.0,
        };
      }

      // 检查当前用户是否已支付（占位逻辑，可替换为后端API）
      final hasPaid = await _checkUserPaymentStatus(groupId, OpenIM.iMManager.userID);

      return {
        'requiresPayment': requiresPayment,
        'hasPaid': hasPaid,
        'fee': fee,
      };
    } catch (e) {
      return {
        'requiresPayment': false,
        'hasPaid': false,
        'fee': 0.0,
      };
    }
  }

  Future<bool> _checkUserPaymentStatus(String groupId, String userId) async {
    try {
      // TODO: 替换为真实后端支付状态查询接口
      await Future.delayed(Duration(milliseconds: 300));
      return false;
    } catch (e) {
      return false;
    }
  }
}
